import 'dart:io';

import 'package:star_author/config/app.dart';
import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/model/backflow.dart';
import 'package:star_author/utils/common_util/date_util.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/string_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:star_author/widgets/alert.dart';
import 'package:star_author/widgets/countdown/count_down_view.dart';
import 'package:star_author/widgets/dialog/dialog_type.dart';
import 'package:star_author/widgets/dialog/sure_dialog.dart';
import 'package:star_author/widgets/select_widget.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class BidderGoodsDetailHandler {
  static void starBackflow(bool isStared, int id, Function callback) {
    String method = isStared ? "DELETE" : "POST";
    HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/backflows/${id}/star',
      method: method,
    ).then(
      (value) {
        callback();
      },
    );
  }

  ///处理 收回货品 按钮
  static void handlerTakeBack(BackflowModel data) {
    Function waitAgainContent = () {
      Alert.showToast(
        Get.context!,
        content: Column(
          children: [
            Text('您的货品很快就可以重新${App.evaluation_text}了\n不要浪费可以高价回收的机会呀～'),
            Builder(builder: (ctx) {
              Duration countDownVal = DateUtil.getDateTime(
                      formatDate(data.can_self_help_evaluated_again_at))!
                  .difference(DateTime.now());
              if (countDownVal.inSeconds < 0) {
                return Container();
              }
              return Container(
                margin: EdgeInsets.only(top: 10.w),
                child: CountdownView(
                  countDownVal,
                  Duration(seconds: 1),
                  (context, remaining) {
                    TextStyle redTextStyle = TextStyle(
                      color: UIConstant.colorE02020,
                      fontSize: 12.sp,
                    );

                    TextStyle grayTextStyle = TextStyle(
                      color: UIConstant.color99,
                      fontSize: 12.sp,
                    );

                    late RichText contextWidget = RichText(text: TextSpan());

                    if (remaining.inSeconds >= 0) {
                      String day = StringUtil.toTwoDigits(remaining.inDays);

                      String hour = StringUtil.toTwoDigits(
                          remaining.inHours.remainder(24));

                      String minute = StringUtil.toTwoDigits(
                          remaining.inMinutes.remainder(60));
                      contextWidget = RichText(
                        text: TextSpan(children: [
                          TextSpan(
                            text: '$day',
                            style: redTextStyle,
                          ),
                          TextSpan(
                            text: '天',
                            style: grayTextStyle,
                          ),
                          TextSpan(
                            text: '$hour',
                            style: redTextStyle,
                          ),
                          TextSpan(
                            text: '时',
                            style: grayTextStyle,
                          ),
                          TextSpan(
                            text: '$minute',
                            style: redTextStyle,
                          ),
                          TextSpan(
                            text: '分后可重新竞拍',
                            style: grayTextStyle,
                          ),
                        ]),
                      );
                    }
                    return contextWidget;
                  },
                  Container(),
                  isStartWhenInit: true,
                ),
              );
            }),
          ],
        ),
        cancelText: '继续收回',
        confirmText: '再等等',
        onConfirm: () {
          Get.back();
        },
        onCancel: () {
          Get.back();
          tackBack(data);
        },
      );
    };

    bool waitAgain = data.has_evaluated_again == false &&
        data.can_evaluated_again == false &&
        data.rejectedReason.isEmpty;

    ///非二次竞拍
    ///如果是我们拒绝他回流,直接弹出列表
    if ((data.evaluated_at != null && data.evaluated_at!.isNotEmpty) &&
        (waitAgain || data.can_evaluated_again)) {
      if (waitAgain) {
        waitAgainContent();
      } else {
        DialogUtil.showMyDialog(
            dialogType: DialogType.firstTakeBack,
            leftButtonOnTap: () async {},
            rightButtonOnTap: () {
              tackBack(data);
            });
      }
    } else {
      tackBack(data);
    }
  }

  static void tackBack(BackflowModel data, {Function? successCallback}) async {
    await HttpUtil.commonRequest(Get.context!, '/api/v1/backflows/present',
        queryParameters: {
          'status': 'back',
          'need_recycle': true,
          "without_clone": true,
          "with_back_address_last": true,
          "per_page": 200
        }).then((value) {
      Map<String, dynamic> map = value.data;
      List list = map['data'];
      List<BackflowModel> backList = [];
      list.forEach((element) {
        BackflowModel data1 = BackflowModel(element);
        if (data1.canBack) {
          if (data.id == data1.id) {
            data1.select = true;
          } else {
            data1.select = false;
          }
          // if(data.backflowReceivedAddress == data1.backflowReceivedAddress){
          backList.add(data1);
          // }
        }
      });

      //把当前点击的设置到第一个位置
      int i = backList.indexWhere((element) => element.id == data.id);
      BackflowModel data1 = backList[i];
      backList.removeAt(i);
      backList.insert(0, data1);
      List<SelectModel<BackflowModel>> selectList =
          backList.asMap().entries.map((entry) {
        return new SelectModel(
          data: entry.value,
          select: entry.key == 0,
          enable: entry.value.backflowReceivedAddress ==
              data.backflowReceivedAddress,
        );
      }).toList();
    });
  }

  static downloadFile(index, String url, List videos) async {
    Dio dio = Dio()
      ..interceptors.add(
        LogInterceptor(requestBody: true, responseBody: true),
      );
    //设置请求头 不然不能访问资源
    dio.options.headers.addAll({
      HttpHeaders.userAgentHeader: 'ExoPlayer',
    });
    bool checkPermission1 = false;
    // 1、读取系统权限的弹框
    if (Platform.isIOS) {
      checkPermission1 = await Permission.photosAddOnly.request().isGranted;
    } else {
      checkPermission1 = await Permission.storage.request().isGranted;
    }
    if (checkPermission1 == true) {
      String dirloc = "";
      if (Platform.isAndroid) {
        dirloc = (await getApplicationSupportDirectory()).path;
      } else {
        dirloc = (await getApplicationDocumentsDirectory()).path;
        dirloc += "/huiliu";
      }
      int timeTemp = DateTime.now().millisecondsSinceEpoch;

      CustomToast.show('开始下载');
      String suffix = "";
      if ((index <= (videos.length) - 1)) {
        suffix = ".mp4";
      } else {
        suffix = ".png";
      }
      String path = dirloc + "/" + timeTemp.toString() + suffix;
      String albumName = "huiliu"; //保存到iOS相册名称
      await dio.download(url, path).then((value) async {
        if (value.statusCode == 200) {
          if (suffix == ".mp4") {
            await GallerySaver.saveVideo(
              path,
              albumName: albumName,
            ).then((value) {
              if (value ?? false) {
                File(path).deleteSync();
                CustomToast.show("下载成功");
              }
            });
          } else if (suffix == '.png') {
            await GallerySaver.saveImage(
              path,
              albumName: albumName,
            ).then((value) {
              if (value ?? false) {
                File(path).deleteSync();
                CustomToast.show("下载成功");
              }
            });
          }
        }
      }).catchError((e) {
        CustomToast.show("下载出错:${e.toString()}");
      });
    } else {
      downloadFile(index, url, videos);
    }
  }
}
